<script setup>
import { ref } from 'vue'
import {
  getRecordsService,
  delRecordsService,
  addRecordService,
  downloadRecordsService
} from '@/api/records'
import { downloadExcel } from '@/utils/downloadExcel'
const recordsList = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const formModel = ref({
  amount: null,
  position: '',
  speciesName: ''
})
const params = ref({
  page: 1,
  pageSize: 5,
  speciesId: '',
  amount: ''
})
const rules = {
  amount: [
    { required: true, message: '请输入数量', trigger: 'blur' },
    { type: 'number', message: '数量必须是数字值', trigger: ['blur', 'change'] }
  ],
  position: [{ required: true, message: '请输入位置', trigger: 'blur' }],
  speciesName: [{ required: true, message: '请输入种类名称', trigger: 'blur' }]
}

const getRecordsList = async () => {
  loading.value = true
  const res = await getRecordsService(params.value)
  recordsList.value = res.data.data.records
  total.value = res.data.data.total
  loading.value = false
}
getRecordsList()

//删除记录
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const handleBatchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的记录')
    return
  }

  ElMessageBox.confirm(`确认删除选中的 ${multipleSelection.value.length} 条记录吗？`, '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const ids = multipleSelection.value.map((item) => item.id)
      console.log('要删除的id列表：', ids)
      await delRecordsService(ids.join(','))
      getRecordsList()
      ElMessage.success('删除成功')
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}
// 添加记录
const onSubmit = async () => {
  const formData = {
    amount: formModel.value.amount,
    species: formModel.value.speciesName,
    position: formModel.value.position
  }

  const res = await addRecordService(formData)
  if (res && res.data.code === 1) {
    ElMessage.success('添加成功')
    dialogVisible.value = false
    formModel.value = { amount: null, position: '', speciesName: '', dateTime: '' }
  } else {
    ElMessage.error(res ? res.data.msg : '添加失败')
  }

  getRecordsList()
}

const onSizeChange = (size) => {
  params.value.pageSize = size
  params.value.page = 1
  getRecordsList()
}
const onCurrentChange = (page) => {
  params.value.page = page
  getRecordsList()
}

//下载记录文件
const onDownLoad = async () => {
  try {
    const res = await downloadRecordsService() // 假设这是一个返回 Promise 的函数
    console.log(res)

    if (res && res.data) {
      downloadExcel(res.data.data, '识别记录.xlsx')
    } else {
      console.error('下载数据为空或格式错误:', res)
    }
  } catch (error) {
    console.error('下载失败:', error)
  }
}
</script>
<template>
  <page-container title="识别记录">
    <template #extra>
      <div class="button-group">
        <el-button @click="onDownLoad" class="buttonDownload">下载记录</el-button>
        <el-button type="primary" @click="dialogVisible = true">新增</el-button>
        <el-button type="danger" :disabled="!multipleSelection.length" @click="handleBatchDelete"
          >删除</el-button
        >
      </div>
    </template>
    <el-table
      v-loading="loading"
      :data="recordsList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="序号" width="100">
        <template #default="{ $index }">
          {{ (params.page - 1) * params.pageSize + $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="白蚁名称" prop="speciesName"></el-table-column>
      <el-table-column label="记录地点" prop="position"></el-table-column>
      <el-table-column label="白蚁数量" prop="amount"></el-table-column>
      <el-table-column label="记录时间" prop="dateTime"></el-table-column>

      <el-table-column type="selection" width="55" />
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <el-pagination
      :current-page="params.page"
      :page-size="params.pageSize"
      :page-sizes="[2, 3, 4, 5, 10]"
      layout="jumper, total, sizes, prev, pager, next"
      background
      :total="total"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
      @update:current-page="params.page = $event"
      @update:page-size="params.pageSize = $event"
      style="margin-top: 20px; justify-content: flex-end"
    />
  </page-container>
  <!-- 添加记录弹窗 -->
  <el-dialog v-model="dialogVisible" title="新增记录" width="30%">
    <el-form
      ref="formRef"
      :model="formModel"
      :rules="rules"
      label-width="100px"
      style="padding-right: 30px"
    >
      <el-form-item label="种类名称" prop="speciesName">
        <el-input v-model="formModel.speciesName"></el-input>
      </el-form-item>
      <el-form-item label="数量" prop="amount">
        <el-input-number v-model="formModel.amount" :min="1"></el-input-number>
      </el-form-item>
      <el-form-item label="位置" prop="position">
        <el-input v-model="formModel.position"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.button-group {
  display: flex;
  gap: 10px;
  align-items: center;

  $button-color: #4cc713;
  $button-hover-color: #45a21a;
  $border-color-hover: #cdefbd;

  .buttonDownload {
    display: inline-block;
    position: relative;
    padding: 10px 25px;
    background-color: $button-color;
    color: white;
    font-family: sans-serif;
    text-decoration: none;
    text-align: center;
    text-indent: 15px;
    border: none;

    &:hover {
      background-color: $button-hover-color;
      color: white;
    }

    &::before,
    &::after {
      content: ' ';
      display: block;
      position: absolute;
      left: 15px;
      top: 52%;
    }

    &::before {
      width: 10px;
      height: 2px;
      border-style: solid;
      border-width: 0 2px 2px;
    }

    &::after {
      width: 0;
      height: 0;
      margin-left: 3px;
      margin-top: -7px;
      border-style: solid;
      border-width: 4px 4px 0 4px;
      border-color: transparent;
      border-top-color: inherit;
      animation: downloadArrow 1s linear infinite;
      animation-play-state: paused;
    }

    &:hover {
      &::before {
        border-color: $border-color-hover;
      }

      &::after {
        border-top-color: $border-color-hover;
        animation-play-state: running;
      }
    }
  }

  @keyframes downloadArrow {
    0% {
      margin-top: -7px;
      opacity: 1;
    }

    0.001% {
      margin-top: -15px;
      opacity: 0.4;
    }

    50% {
      opacity: 1;
    }

    100% {
      margin-top: 0;
      opacity: 0.4;
    }
  }
}
</style>
